package com.example.web_flux.controller;

import com.oracle.tools.packager.Log;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

/**
 * @auth 罗俊华
 * @Date 2022/8/14 12:34 上午
 */

@RestController
@AllArgsConstructor
@Slf4j
public class StreamController {

    private Executor executor;

    @GetMapping("/streamHello")
    public ResponseBodyEmitter hello() throws IOException {
        ResponseBodyEmitter result = new ResponseBodyEmitter();
        CompletableFuture.runAsync(()->{
            for (int i = 0; i < 3; i++) {
                try {
                    log.info("准备第{}次发送数据",i);
                    result.send("你好" + i);
                    TimeUnit.SECONDS.sleep(1);
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            result.complete();
        });
        log.info("响应完成");
        return result;
    }
}
